﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage.Pickers;
using Windows.Storage;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Popups;


// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudyTime_1
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class cardBuilder : StudyTime_1.Common.LayoutAwarePage
    {
        public List<studyCard> studyList = new List<studyCard>();
        private bool saveLocation = false;
        private string filePath;
        private string fileName = "goo.xml";
        private StorageFile storage;
        private StorageFile tempStorage;
        private Stream outStream;
        private DataContractSerializer xml;
        private bool shownMessage = false;


        public cardBuilder()
        {
            this.InitializeComponent();
        }


        async private void append(List<studyCard> convert)
        {
            try
            {
                var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
                outStream = file.AsStreamForWrite();

                xml.WriteObject(outStream, convert);

                await outStream.FlushAsync();
                file.Dispose();

                errorBox.Text = "Saved Successfully!";
            }
            catch (IOException)
            {
                errorBox.Text = "Cannot write to the file";
            }

        }


        async public void selection()
        {

            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.Downloads;
            savePicker.SuggestedFileName = "studycard";
            savePicker.DefaultFileExtension = ".studycardxml";   
            savePicker.FileTypeChoices.Add("STUDYCARD", new List<string>() { ".studycardxml" });

            if (storage != null)
                {
                    tempStorage = storage;
                }
           
            storage = await savePicker.PickSaveFileAsync();
            

            if (null != storage)
            {
                // Application now has read/write access to the picked file
                filePath = storage.Path;
                fileName = storage.Name;
                saveLocation = true;
                SerializeXML(studyList);

            }
            else
            {
                storage = tempStorage;
                errorBox.Text = "File was not returned";
            }
        }

        async private void SerializeXML(List<studyCard> convert)
        {

            try
            {
                var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
                outStream = file.AsStreamForWrite();



                xml = new DataContractSerializer(typeof(List<studyCard>));


                xml.WriteObject(outStream, convert);

                await outStream.FlushAsync();
                file.Dispose();

                errorBox.Text = "Saved Successfully!";
            }
            catch (IOException)
            {
                errorBox.Text = "Cannot write to the file";
            }

        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void addCard_Click(object sender, RoutedEventArgs e)
        {
            studyCard card = new studyCard();
            card.question = question.Text.ToString();
            card.answer = answer.Text.ToString();

            studyList.Add(card);

            errorBox.Text = studyList.Count.ToString() + " " + "Items Added";
            answer.Text = "";
            question.Text = "";

            if (saveLocation == true)
            {
                append(studyList);
            }
            else
            {
                saveAll.IsEnabled = true;
            }

        }

        private async void saveAll_Click(object sender, RoutedEventArgs e)
        {
            if (shownMessage == false)
            {
                var mDialog = new MessageDialog("You only need to export once. After first export each added item will be appended to the saved file.");
                await mDialog.ShowAsync();
                shownMessage = true;
            }
            else
            {
            }
            selection();
        }

        private void pageRoot_Loaded(object sender, RoutedEventArgs e)
        {
            saveAll.IsEnabled = false;

            Storyboard sb = this.FindName("cardBuilderStory") as Storyboard;
            if (sb != null)
            {
                sb.Begin();
            }
        }
    }
}
